package com.jmyd.coupon.server.interceptors;

import com.alibaba.fastjson.JSON;
import com.jmyd.commons.base.vo.Result;
import com.jmyd.commons.enums.SystemErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author samphin
 * @date 2021/3/18 15:20
 */
@Slf4j
public abstract class BaseInterceptor extends HandlerInterceptorAdapter {

    /**
     * 组装返回对象
     *
     * @param response        响应对象
     * @param systemErrorEnum 错误码
     */
    protected boolean returnResponseData(HttpServletResponse response, SystemErrorEnum systemErrorEnum) {
        try {
            Result<?> result = Result.failure(systemErrorEnum);
            response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }
}
